﻿using SketchUpAPI.NET.Enums;
using SketchUpAPI.NET.SketchUp.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SketchUpAPI.NET.Objects
{
    /// <summary>
    /// 环
    /// </summary>
    /// <remarks>对 SketchUpAPI 中的 SULoopRef 的包装</remarks>
    public class Loop : Entity
    {
        private enum LoopWinding
        {
            /// <summary>
            /// 逆时针 CounterClockWise
            /// </summary>
            SULoopWinding_CCW,

            /// <summary>
            /// 顺时针 ClockWise
            /// </summary>
            SULoopWinding_CW
        }

        #region API 函数
        /// <summary>
        /// 环包含的顶点个数
        /// </summary>
        /// <param name="loop"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SULoopGetNumVertices(IntPtr loop, out long count);

        /// <summary>
        /// 环包含的顶点
        /// </summary>
        /// <param name="loop"></param>
        /// <param name="len"></param>
        /// <param name="vertices"></param>
        /// <param name="realcount"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SULoopGetVertices(IntPtr loop, long len, IntPtr[] vertices, out long realcount);

        /// <summary>
        /// 判断环是顺时针还是逆时针
        /// </summary>
        /// <param name="loop"></param>
        /// <param name="zDirection"></param>
        /// <param name="orientation"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SULoopGetWinding(IntPtr loop, Vector3D zDirection, out LoopWinding orientation);
        #endregion

        /// <summary>
        /// 换包含的全部顶点
        /// </summary>
        public List<Vertex> Vertices
        {
            get
            {
                SketchUpExceptionHelper.ThrowSUResult(SULoopGetNumVertices(Id, out long count));
                IntPtr[] ptrs = new IntPtr[count];
                SketchUpExceptionHelper.ThrowSUResult(SULoopGetVertices(Id, count, ptrs, out long realcount));
                return ptrs.Select(pt => new Vertex(pt)).ToList();
            }
        }

        internal Loop(IntPtr id)
        {
            Id = id;
        }

        /// <summary>
        /// 是否是顺时针
        /// </summary>
        /// <param name="zDir">Z 方向</param>
        /// <returns></returns>
        public bool IsClockWise(Vector3D zDir)
        {
            SketchUpExceptionHelper.ThrowSUResult(SULoopGetWinding(Id, zDir, out LoopWinding ori));
            return ori == LoopWinding.SULoopWinding_CCW;
        }
    }
}